package org.dbstar.scheduler.control.db.authority;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.dbstar.scheduler.beans.User;
import org.dbstar.scheduler.control.AuthorityController;
import org.dbstar.scheduler.control.db.JdbcTemplateDao;
import org.dbstar.scheduler.control.exception.DaoException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;


/**
 * 使用JdbcTemplate的AuthorityController实现类。
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-6-5
 */
public class JdbcTemplateAuthorityController extends JdbcTemplateDao implements AuthorityController {
	private final AuthorityQueryUsername queryUsername;
	private final AuthorityDelete delete;
	private final AuthorityInsert insert;

	public JdbcTemplateAuthorityController(JdbcTemplate jt) {
		super(jt);
		this.queryUsername = new AuthorityQueryUsername(jt);
		this.delete = new AuthorityDelete(jt);
		this.insert = new AuthorityInsert(jt);
	}

	@Override
	public List<String> getAllUsers() throws DaoException {
		try {
			return queryUsername.execute();
		} catch (Throwable e) {
			throw new DaoException(e);
		}
	}

	@Override
	public User getUser(final String username) throws DaoException {
		String sql = "SELECT * FROM SCHD_AUTHORITY WHERE USERNAME=?";
		try {
			return jt.query(sql, new PreparedStatementSetter() {
				@Override
				public void setValues(PreparedStatement ps) throws SQLException {
					ps.setString(1, username);
				}
			}, new ResultSetExtractor<User>() {
				@Override
				public User extractData(ResultSet rs) throws SQLException, DataAccessException {
					if (rs.next()) {
						User user = new User();
						user.setUsername(rs.getString("USERNAME"));
						user.setDisplayName(rs.getString("DISPLAY_NAME"));
						user.addAuthority(rs.getString("AUTHORITY"));
						while (rs.next()) {
							user.addAuthority(rs.getString("AUTHORITY"));
						}
						return user;
					} else {
						return null;
					}
				}
			});
		} catch (Throwable e) {
			throw new DaoException(e);
		}
	}

	@Override
	public void update(User user) throws DaoException {
		try {
			delete.delete(user);
			insert.insert(user);
		} catch (Throwable e) {
			throw new DaoException(e);
		}
	}
}
